<template>
  <el-dialog title="积分审批" v-model="openAuditDialog" width="1250px" append-to-body>
    <el-form :model="queryOrgParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="99px" style="padding-right: 5px;">
      <el-row>
        <el-col :span="10">
          <el-form-item label="申报时间" prop="createTime" style="width: 100%;">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 100%;"
              ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="积分分类" prop="" style="width: 100%;">
            <el-select v-model="queryOrgParams.typeId" placeholder="请选择积分分类" clearable>
                <el-option
                  v-for="dict in scoreTypeOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="年份" prop="yearSign" style="width: 100%;">
            <el-select v-model="queryOrgParams.yearSign" placeholder="请选择年份" clearable>
                <el-option
                  v-for="dict in yearOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="申报对象" prop="userName" style="width: 100%;">
            <el-input
              v-model="queryOrgParams.userName"
              placeholder="请输入申报对象"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <div class="search-container">
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="danger" icon="Search" @click="handleQuery">查询</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleTabClick">
        <el-tab-pane label="积分申报" name="first">
            <div style="display: flex; align-items: left; justify-content: flex-start; margin: 10px 0px;" v-if="isApprove">
                <el-button type="success" @click="showRefuseDialog(null, false, 'pass')">批量通过</el-button>
                <el-button type="danger" @click="showRefuseDialog(null, false, 'refuse')">批量驳回</el-button>
            </div>
        </el-tab-pane>
        <el-tab-pane label="驳回" name="second" style="height: 100% !important;"></el-tab-pane>
        <el-tab-pane label="同意" name="third" style="height: 100% !important;"></el-tab-pane>
    </el-tabs>

    <el-table v-loading="loading" :data="orgScoreList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="申报时间" align="center" prop="createTime"/>
        <el-table-column label="申报对象" align="center" prop="orgName">
          <template #default="scope">
              <span>{{ typeVal === 0 ? scope.row.userName : scope.row.orgName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属组织" align="center" prop="orgName"/>
        <el-table-column label="积分分类" align="center" prop="typeName"/>
        <el-table-column label="积分内容" align="center" prop="title"/>
        <el-table-column label="申报周期" align="center" prop="cycle" width="150px">
          <template #default="scope">
              <!-- 0：月度；1：季度；2：半年 3：年度 -->
              <div v-if="scope.row.cycle==0">
                {{ scope.row.yearSign }}年{{ selectDictLabel(monthOptions, scope.row.cycleValue) }}
              </div>
              <div v-else-if="scope.row.cycle==1">
                {{ scope.row.yearSign }}年{{ selectDictLabel(jiDuOptions, scope.row.cycleValue) }}
              </div>
              <div v-else-if="scope.row.cycle==2">
                {{ scope.row.yearSign }}年{{ selectDictLabel(halfYearOptions, scope.row.cycleValue) }}
              </div>
              <div v-else-if="scope.row.cycle==3">{{ scope.row.cycleValue }}年度</div>
              <div v-else>&nbsp;</div>
          </template>
        </el-table-column>
        <el-table-column label="积分上限" align="center" prop="scoreDayUp"/>-->
        <el-table-column label="申报分数" align="center" prop="addScore"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
          <template #default="scope">
            <a href="#" style="color: red;" @click="showRefuseDialog(scope.row, true, 'pass')" v-if="isApprove">通过</a>
            <el-divider direction="vertical" v-if="isApprove"/>
            <a href="#" style="color: red;" @click="showRefuseDialog(scope.row, true, 'refuse')" v-if="isApprove">驳回</a>
            <el-divider direction="vertical" v-if="isApprove"/>
            <a href="#" style="color: red;" @click="viewRemark(scope.row)">查看原因</a>
          </template>
        </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryOrgParams.pageNum"
      v-model:limit="queryOrgParams.pageSize"
      @pagination="getScoreList"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelAudit">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <add-remark ref="addRemarkRef" @callBack="callBackRemark"/>
  
  <!-- 驳回弹窗 -->
  <el-dialog :title="passRefuseTitle" v-model="openViewRefuse" width="1100px" append-to-body>
      <el-form ref="refuseRef" :model="refuseForm" :rules="refuseRules" label-width="90px" style="padding: 19px;">
        <el-row v-if="refuseForm.refuseType === 'refuse'">
            <el-col :span="24">
                <el-form-item label="填写原因:" prop="remark">
                    <el-input
                        v-model="refuseForm.remark"
                        type="textarea"
                        :rows="5"
                    />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row v-if="refuseForm.isSingle">
          <el-col :span="8">
              <el-form-item label="申报时间:">{{ refuseForm.createTime }}</el-form-item>
          </el-col>
          <el-col :span="8">
              <el-form-item label="申报对象:">{{ typeVal === 0 ? refuseForm.userName : refuseForm.orgName }}</el-form-item>
          </el-col>
          <el-col :span="8">
              <el-form-item label="所属组织:">{{ refuseForm.orgName }}</el-form-item>
          </el-col>
          <el-col :span="8">
              <el-form-item label="积分分类:">{{ refuseForm.typeName }}</el-form-item>
          </el-col>
          <el-col :span="8">
              <el-form-item label="申报周期:">
                <div v-if="refuseForm.cycle==0">
                  {{ refuseForm.yearSign }}年{{ selectDictLabel(monthOptions, refuseForm.cycleValue) }}
                </div>
                <div v-else-if="refuseForm.cycle==1">
                  {{ refuseForm.yearSign }}年{{ selectDictLabel(jiDuOptions, refuseForm.cycleValue) }}
                </div>
                <div v-else-if="refuseForm.cycle==2">
                  {{ refuseForm.yearSign }}年{{ selectDictLabel(halfYearOptions, refuseForm.cycleValue) }}
                </div>
                <div v-else-if="refuseForm.cycle==3">{{ refuseForm.cycleValue }}年度</div>
                <div v-else>&nbsp;</div>
              </el-form-item>
          </el-col>
          <el-col :span="8">
              <el-form-item label="申报分数:">{{ refuseForm.addScore }}</el-form-item>
          </el-col>
          <el-col :span="24">
              <el-form-item label="积分内容:">{{ refuseForm.title }}</el-form-item>
          </el-col>
        </el-row>
        <el-table :data="refuseList" v-else>
          <el-table-column label="申报时间" align="center" prop="createTime"/>
          <el-table-column label="申报对象" align="center" prop="orgName">
            <template #default="scope">{{ typeVal }}
                <span>{{ typeVal === 0 ? scope.row.userName : scope.row.orgName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属组织" align="center" prop="orgName"/>
          <el-table-column label="积分分类" align="center" prop="typeName"/>
          <el-table-column label="积分内容" align="center" prop="title"/>
          <el-table-column label="申报周期" align="center" prop="cycle" width="150px">
            <template #default="scope">
                <!-- 0：月度；1：季度；2：半年 3：年度 -->
                <div v-if="scope.row.cycle==0">
                  {{ scope.row.yearSign }}年{{ selectDictLabel(monthOptions, scope.row.cycleValue) }}
                </div>
                <div v-else-if="scope.row.cycle==1">
                  {{ scope.row.yearSign }}年{{ selectDictLabel(jiDuOptions, scope.row.cycleValue) }}
                </div>
                <div v-else-if="scope.row.cycle==2">
                  {{ scope.row.yearSign }}年{{ selectDictLabel(halfYearOptions, scope.row.cycleValue) }}
                </div>
                <div v-else-if="scope.row.cycle==3">{{ scope.row.cycleValue }}年度</div>
                <div v-else>&nbsp;</div>
            </template>
          </el-table-column>
          <el-table-column label="申报分数" align="center" prop="addScore"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
            <template #default="scope">
              <a href="#" style="color: red;" @click="viewRemark(scope.row)">查看原因</a>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <el-divider  style="margin: 0; border-top : 1px solid #e8e8e8;" v-if="refuseForm.isSingle"/>
      <template #footer>
      <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">{{ refuseForm.refuseType === 'pass'? '通 过' : '驳 回' }}</el-button>
          <el-button @click="cancelForm">取 消</el-button>
      </div>
      </template>
  </el-dialog>

</template>
  
<script setup>
  import { listScoreType } from "@/api/partybuilding/ScoreType";
  import { approvalListOrg, approvalList, approve, approveOrg } from "@/api/partybuilding/WorkScore";
  import { ref } from "vue";
  import AddRemark from './AddRemark.vue'
  const openAuditDialog = ref(false);
  const { proxy } = getCurrentInstance();
  const loading = ref(true);
  const showSearch = ref(true);
  const orgScoreList = ref([]);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const typeVal = ref(null);
  const yearOptions = ref([]);
  const monthOptions = ref([]);
  const jiDuOptions = ref([]);
  const halfYearOptions = ref([]);
  const curYear = ref(null);
  curYear.value = new Date().getFullYear();
  const activeName = ref("first");
  const dateRange = ref([]);
  const scoreTypeOptions = ref([]);
  const addRemarkRef = ref(null);
  const isApprove = ref(false);
  const openViewRefuse = ref(false);
  const refuseList = ref([]);
  const passRefuseTitle = ref(null);
  const data = reactive({
    form: {},
    queryOrgParams: {
      pageNum: 1,
      pageSize: 10,
      userName: null,
      deptId: null,
      yearSign: null,
      typeId: null,
      orderByName:"createTime",
      descIs:true,
      approvalStatus: 0 // approvalStatus-0待审核，10000审核结束通过,-10000审核结束驳回
    },
    rules: {},
    refuseForm: {
      isSingle: true,
      id: null,
      remark: '',
      refuseType: null,
    },
    refuseRules: {
      remark: [
        { required: true, message: '请输入驳回原因', trigger: 'blur' }
      ]
    }
  });
  const { form, queryOrgParams, rules, refuseForm, refuseRules } = toRefs(data);
  // 初始化字典列表
  function getInitDictOptions() {
    const curYearValue = new Date().getFullYear();
    yearOptions.value = [];
    for (let i = curYearValue; i > curYearValue - 5; i--) {
      yearOptions.value.push({ value: i, label: i + "年" });
    }
    queryOrgParams.value.yearSign = curYearValue;
    monthOptions.value = [];
    for (let i = 1; i <= 12; i++) {
      monthOptions.value.push({ value: i, label: i + "月" });
    }
    jiDuOptions.value = [];
    jiDuOptions.value.push({ value: 1, label: "第一季度" });
    jiDuOptions.value.push({ value: 2, label: "第二季度" });
    jiDuOptions.value.push({ value: 3, label: "第三季度" });
    jiDuOptions.value.push({ value: 4, label: "第四季度" });
    halfYearOptions.value = [];
    jiDuOptions.value.push({ value: 1, label: "上半年" });
    jiDuOptions.value.push({ value: 2, label:  "下半年" });
  }
  const refresh = (deptId, year, type) => {
    activeName.value = "first";
    queryOrgParams.value.yearSign = year;
    typeVal.value = type;
    if (typeVal.value == 0) {//0个人积分，1组织积分
      queryOrgParams.value.userId = deptId;
      queryOrgParams.value.deptId = undefined;
    } else {
      queryOrgParams.value.userId = undefined;
      queryOrgParams.value.deptId = deptId;
    }
    queryOrgParams.value.approvalStatus = 0;
    isApprove.value = true;
    getScoreTypeOptions();
    getScoreList();
  };
  
  defineExpose({
      refresh
  });

  function handleTabClick(tab) {
    activeName.value = tab.props.name;
    if (activeName.value === 'first') {
      queryOrgParams.value.approvalStatus = 0;
      isApprove.value = true;
    } else if (activeName.value ==='second') {
      queryOrgParams.value.approvalStatus = -10000;
      isApprove.value = false;
    } else if (activeName.value === 'third') {
      queryOrgParams.value.approvalStatus = 10000;
      isApprove.value = false;
    }
    getScoreList();
  }

function viewRemark(row) {
  addRemarkRef.value.addRemarkDialog(row.remark, 'view', true);
}

// 获取积分分类
function getScoreTypeOptions() {
  let obj = {};
  obj.type = typeVal.value;//0个人积分，1组织积分
  obj.level = 0;
  scoreTypeOptions.value = [];
  listScoreType(obj).then(response => {
    let tmpArry = response.rows;
    tmpArry.forEach(item => {
      scoreTypeOptions.value.push({ value: item.id, label: item.name });
    });
  });
}

/** 选择条数  */
function handleSelectionChange(selection) {
    refuseList.value = selection;
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
};

/** 搜索按钮操作 */
function handleQuery() {
  queryOrgParams.value.pageNum = 1;
  getScoreList();
}
function resetVo() {
  queryOrgParams.value = {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    deptId: null,
    yearSign: curYear.value,
    typeId: null,
    approvalStatus: 0
  };
  dateRange.value = [];
  proxy.resetForm("queryRef");
}

/** 重置按钮操作 */
function resetQuery() {
  resetVo();
  handleQuery();
}

// 查询积分
function getScoreList() {
  if (typeVal.value == 0) {//0个人积分，1组织积分
    getMemberScoreList();
  } else {
    getOrgScoreList();
  }
}

/** 查询党员积分列表 */
function getMemberScoreList() {
  loading.value = true;
  let obj = {};
  obj.createTime = dateRange.value? dateRange.value[0]: null;
  obj.createTime2 = dateRange.value? dateRange.value[1]: null;
  obj.typeId = queryOrgParams.value.typeId;
  obj.yearSign = queryOrgParams.value.yearSign;
  obj.userName = queryOrgParams.value.userName;
  obj.approvalStatus = queryOrgParams.value.approvalStatus;
  approvalList(queryOrgParams.value, obj).then(response => {
    openAuditDialog.value = true;
    let tmpArry = response.rows;
    tmpArry.forEach(item => {
      if (queryOrgParams.value.approvalStatus !=0 ){
        item.remark = item.approvalRemark;
      }
    });
    orgScoreList.value = proxy.handleTree(tmpArry);
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询组织积分列表 */
function getOrgScoreList() {
  loading.value = true;
  let obj = {};
  obj.createTime = dateRange.value? dateRange.value[0]: null;
  obj.createTime2 = dateRange.value? dateRange.value[1]: null;
  obj.typeId = queryOrgParams.value.typeId;
  obj.yearSign = queryOrgParams.value.yearSign;
  obj.orgName = queryOrgParams.value.userName;
  obj.approvalStatus = queryOrgParams.value.approvalStatus;
  approvalListOrg(queryOrgParams.value, obj).then(response => {
    openAuditDialog.value = true;
    let tmpArry = response.rows;
    tmpArry.forEach(item => {
      if (queryOrgParams.value.approvalStatus !=0 ){
        item.remark = item.approvalRemark;
      }
    });
    orgScoreList.value = proxy.handleTree(tmpArry);
    total.value = response.total;
    loading.value = false;
  });
}

// 显示驳回弹窗
function showRefuseDialog(row, isSingle, refuseType) {
  passRefuseTitle.value = refuseType === 'pass' ? '通过原因' : '驳回原因';
  if (isSingle) {
    // 单个驳回
    refuseForm.value = row;
    refuseForm.value.isSingle = true;
    refuseForm.value.id = row.id;
    refuseForm.value.refuseType = refuseType;
  }else{
    let titleStr = refuseType === 'pass'? '通过' : '驳回';
    // 批量驳回
    if (ids.value.length == 0) {
      proxy.$modal.msgError("请选择要"+titleStr+"的记录");
      return;
    }
    refuseForm.value.isSingle = false;
    refuseForm.value.refuseType = refuseType;
  }
  refuseForm.value.remark = "";
  openViewRefuse.value = true;
}

// 提交通过和驳回
function submitForm() {
  proxy.$refs["refuseRef"].validate(valid => {
      if (valid) {
        if (refuseForm.value.isSingle) {
          if (refuseForm.value.refuseType === 'pass'){
            // 单个通过
            auditPass(refuseForm.value);
          }else{
            // 单个驳回
            auditFail(refuseForm.value);
          }
        }else{
          if (refuseForm.value.refuseType === 'pass'){
            // 批量通过
            batchPass();
          }else{
            // 批量驳回
            batchFail();
          }
        }
      }
    });
}

// 取消驳回
function cancelForm() {
  openViewRefuse.value = false;
}

/** 审核通过 */
function auditPass(row) {
  let paramObj = {};
  paramObj.isPass = true;
  paramObj.remark = "审核通过";
  let dataArry = [];
  dataArry.push(row.id);
  proxy.$modal.confirm('是否确认审核通过当前数据项？').then(function() {
      if (typeVal.value == 0) {//0个人积分，1组织积分
        return approve(paramObj, dataArry);
      } else {
        return approveOrg(paramObj, dataArry);
      }
  }).then(() => {
      getScoreList();
      openViewRefuse.value = false;
      proxy.$modal.msgSuccess("审核通过成功");
  }).catch(() => {});
}

/** 审核驳回 */
function auditFail(row) {
  let paramObj = {};
  paramObj.isPass = false;
  paramObj.remark = row.remark;
  let dataArry = [];
  dataArry.push(row.id);
  proxy.$modal.confirm('是否确认审核驳回当前数据项？').then(function() {
      if (typeVal.value == 0) {//0个人积分，1组织积分
        return approve(paramObj, dataArry);
      } else {
        return approveOrg(paramObj, dataArry);
      }
  }).then(() => {
      getScoreList();
      openViewRefuse.value = false;
      proxy.$modal.msgSuccess("审核驳回成功");
  }).catch(() => {});
}

// 批量通过
function batchPass() {
  let paramObj = {};
  paramObj.isPass = true;
  paramObj.remark = "批量通过";
  let dataArry = [];
  ids.value.forEach(item => {
    dataArry.push(item);
  });
  proxy.$modal.confirm('是否确认批量通过所选数据项？').then(function() {
      if (typeVal.value == 0) {//0个人积分，1组织积分
        return approve(paramObj, dataArry);
      } else {
        return approveOrg(paramObj, dataArry);
      }
  }).then(() => {
      getScoreList();
      openViewRefuse.value = false;
      proxy.$modal.msgSuccess("批量通过成功");
  }).catch(() => {});
}

// 批量驳回
function batchFail() {
  let paramObj = {};
  paramObj.isPass = false;
  paramObj.remark = refuseForm.remark;
  let dataArry = [];
  ids.value.forEach(item => {
    dataArry.push(item);
  });
  proxy.$modal.confirm('是否确认批量驳回所选数据项？').then(function() {
      if (typeVal.value == 0) {//0个人积分，1组织积分
        return approve(paramObj, dataArry);
      } else {
        return approveOrg(paramObj, dataArry);
      }
  }).then(() => {
      getScoreList();
      openViewRefuse.value = false;
      proxy.$modal.msgSuccess("批量驳回成功");
  }).catch(() => {});
}

function cancelAudit() {
  resetVo();
  openAuditDialog.value = false;
}

getInitDictOptions();
</script>
  
<style lang="scss" scoped>
  .search-container {
      display: flex;
      align-items: right;
      justify-content: flex-end;
  }
</style>
